//
//  AppDelegate+GT.m
//  NewMyToken
//
//  Created by SZJ on 2021/3/18.
//  Copyright © 2021 Bibox. All rights reserved.
//

#import "AppDelegate+GT.h"
//#import "MTPushAuthAlertView.h"
//#import "MyToken_News-Swift.h"


@implementation AppDelegate (GT)


//+ (void)gt_beginWork{
//    [AppDelegate.shareObject gt_beginWork];
//}


- (void)gt_beginWork{
    [GeTuiSdk setChannelId:@"NMT-Chnanel"];
    // 个推
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    // 注册 APNs
    [self registerRemoteNotification];
    
    [GeTuiSdk resetBadge];
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

/** 注册 APNs */
- (void)registerRemoteNotification {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
    if (@available(iOS 10.0, *)) {
        if (NSClassFromString(@"UNUserNotificationCenter")) {
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            center.delegate = self;
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
                if (!error) {
                    NSLog(@"request authorization succeeded!");
                    if (granted) {
                        //点击允许
                    } else {
                        //点击不允许
                    }
                }
            }];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
            UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
        }
    } else {
        // Fallback on earlier versions
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        } else {
            UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                           UIRemoteNotificationTypeSound |
                                                                           UIRemoteNotificationTypeBadge);
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
        }
    }
}




- (void)gt_application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSUInteger len = [deviceToken length];
    char *chars = (char *) [deviceToken bytes];
    NSMutableString *hexString = [[NSMutableString alloc] init];
    for (NSUInteger i = 0; i < len; i++) {
        [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", chars[i]]];
    }
    // 向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:hexString];
}

/// 通知展示（iOS10及以上版本）
/// @param center center
/// @param notification notification
/// @param completionHandler completionHandler
- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification completionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APNs] %@ \n%@", NSStringFromSelector(_cmd), notification.request.content.userInfo];
//    [self.homePage logMsg:msg];
    // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要，判断是否要提示用户Badge、Sound、Alert等
    //completionHandler(UNNotificationPresentationOptionNone); 若不显示通知，则无法点击通知
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

/// 收到通知信息
/// @param userInfo apns通知内容
/// @param center UNUserNotificationCenter（iOS10及以上版本）
/// @param response UNNotificationResponse（iOS10及以上版本）
/// @param completionHandler 用来在后台状态下进行操作（iOS10以下版本）
- (void)GeTuiSdkDidReceiveNotification:(NSDictionary *)userInfo notificationCenter:(UNUserNotificationCenter *)center response:(UNNotificationResponse *)response fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APNs] %@ \n%@", NSStringFromSelector(_cmd), userInfo];
//    [self.homePage logMsg:msg];
    if(completionHandler) {
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
        completionHandler(UIBackgroundFetchResultNoData);
    }
}


/// 收到透传消息
/// @param userInfo    推送消息内容
/// @param fromGetui   YES: 个推通道  NO：苹果apns通道
/// @param offLine     是否是离线消息，YES.是离线消息
/// @param appId       应用的appId
/// @param taskId      推送消息的任务id
/// @param msgId       推送消息的messageid
/// @param completionHandler 用来在后台状态下进行操作（通过苹果apns通道的消息 才有此参数值）
- (void)GeTuiSdkDidReceiveSlience:(NSDictionary *)userInfo fromGetui:(BOOL)fromGetui offLine:(BOOL)offLine appId:(NSString *)appId taskId:(NSString *)taskId msgId:(NSString *)msgId fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // [ GTSDK ]：汇报个推自定义事件(反馈透传消息)，开发者可以根据项目需要决定是否使用, 非必须
    // [GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APN] %@ \nReceive Slience: fromGetui:%@ appId:%@ offLine:%@ taskId:%@ msgId:%@ userInfo:%@ ", NSStringFromSelector(_cmd), fromGetui ? @"个推消息" : @"APNs消息", appId, offLine ? @"离线" : @"在线", taskId, msgId, userInfo];
//    [self.homePage logMsg:msg];

    if(completionHandler) {
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {
    // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
}


- (void)GeTuiSdkDidOccurError:(NSError *)error {
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [GeTuiSdk GeTuiSdkDidOccurError]:%@\n\n",error.localizedDescription];

    // SDK发生错误时，回调异常错误信息
    NSLog(@"%@", msg);
}



/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    SQ_LOG(@"%@",clientId);
    //个推SDK已注册，返回clientId
//    if (!isNilString(clientId)) {
//        [NMTUser sharedObject].deviceToken = clientId;
//        [DMAppConfig getConfigSuccess:nil failure:nil];
//    }
}

+ (void)lookPushStatus_IfNot_ShowAlertGetAuth{
//    NSDate *date = NSDate.date;
//    NSDateFormatter *formatter = NSDateFormatter.alloc.init;
//    [formatter setDateFormat:@"dd"];
//    int day = [formatter stringFromDate:date].intValue;
//    [formatter setDateFormat:@"yyyy-MM-dd"];
//    NSString *fullDayStr = [formatter stringFromDate:date];
//
//    NSString *pushStatusStr = [NSUserDefaults.standardUserDefaults objectForKey:@"mt_pushStatus"];
//    /// 如果 今天 展示过了  就不展示了
//    if (pushStatusStr && [pushStatusStr isEqualToString:fullDayStr]) {return;}
//    /// 只有 每个月的 1号 和  2号 展示
//    if (!isnan(day) && day > 2) {return;}
//
//    /// 如果系统推送 没打开 就去 系统设置
//    /// 如果应用内推送 没打开  就去 推送设置页面
//    void(^showAuth)(BOOL) = ^(BOOL isSystem){
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [NSUserDefaults.standardUserDefaults setObject:fullDayStr forKey:@"mt_pushStatus"];
//            [NSUserDefaults.standardUserDefaults synchronize];
//            [MTPushAuthAlertView show:^{
//                if (isSystem) {
//                    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
//                       [[UIApplication sharedApplication] openURL:url];
//                    }
//                }else{
//                    [AppDelegate.shareObject.topViewController.navigationController pushViewController:NMTMessageNoticeViewController.new animated:YES];
//                }
//            }];
//        });
//
//    };
//
//    void (^mt_noticeAuth)(BOOL) = ^(BOOL isOpen){
//        if (isOpen) {
//            /// 判断应用内 推送开关   是否打开
//            id alams = [groupDefaults() objectForKey:@"DMAppCofigAlarmStatus"];
//            if (alams == nil || ![alams boolValue]) {showAuth(NO);}
//        }else{
//            showAuth(YES);
//        }
//    };
//
//    /// 判断 系统 推送是否打开
//
//    if (@available(iOS 10 , *))
//    {
//        [UNUserNotificationCenter.currentNotificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
//            switch (settings.authorizationStatus) {
//                case UNAuthorizationStatusDenied:
//                    mt_noticeAuth(NO);
//                    break;
//                default:
//                    mt_noticeAuth(YES);
//                    break;
//            }
//        }];
//    }
}

@end
